using System.Net;
using System.Net.Mail;
using CMS.Application.Common.Interface;
using CMS.Application.RequestDto;
using CMS.Domain.Entity;

namespace CMS.Api.Controllers
{
    public class EmailServser
    {

        private readonly IRepository<Register> _register;
        private readonly IRepository<Users> _Users;
        private readonly string Email;


        public EmailServser(IRepository<Register> register, IRepository<Users> Users,string _Email)
        {
            _register = register;
            _Users = Users;
             Email = _Email;
        }




/// <summary>
/// 发送验证码的静态类
/// </summary>
/// <returns></returns>
        public async Task<object> ToEmail()
        {

            // 实例化一个Random
            Random rm = new Random();

            //循环拼接出一个六位数的验证码
            var Code = "";

            for (int i = 0; i < 6; i++)
            {

                Code += Convert.ToInt32(rm.NextDouble() * 9);

            }

            // 邮件内容
            string Text = "我们十分欢迎您的加入";


            // Creadentials登录SMTP服务器的身份验证
            SmtpClient mailClient = new SmtpClient("smtp.qq.com");

            mailClient.EnableSsl = true;

            mailClient.UseDefaultCredentials = false;

            // 发送邮箱的验证
            mailClient.Credentials = new NetworkCredential("1589953126@qq.com", "vjgysyunszbxiddj");

            // 发件邮箱和收件邮箱
            MailMessage message = new MailMessage(new MailAddress("1589953126@qq.com"), new MailAddress(Email));

            // 邮箱内容
            message.Body = Text;

            // 邮箱主题
            message.Subject = "您的验证码为：" + Code;

            try
            {

                // 发送验证
                mailClient.Send(message);

                /// <summary>
                /// 发送成功后将数据加入注册表
                /// </summary>
                /// <value></value>
                var register = new Register
                {

                    Email = Email,

                    AuthCode = Code

                };


                // 在注册表内判断改邮箱是否存在
                var InEmail = _register.Table.FirstOrDefault(x => x.Email == Email);
                


                if (InEmail != null)
                {

                    // 验证码存在更新验证码
                    var IEmail=await _register.GetByIdAsync(InEmail.Id);
                    IEmail.AuthCode=Code;
                    await _register.UpdateAsync(IEmail);


                }
                else
                {
                    // 不存在我们添加数据
                    await _register.AddAsync(register);
                }


                return new
                {
                    Code = "200",
                    msg = "发送成功",
                    data = ""
                };



            }
            catch
            {

                return new
                {
                    Code = "400",
                    msg = "发送失败,请查看邮箱是否正确",
                    data = ""
                };
            }




        }





    }
}